package org.jeecgframework.core.common.controller;

import com.github.miemiedev.mybatis.paginator.domain.PageList;
import com.github.miemiedev.mybatis.paginator.domain.Paginator;
import net.lahuobao.enums.EFileType;
import net.lahuobao.enums.EOSSFolderName;
import net.lahuobao.util.OSSFileOSUtil;
import net.sf.json.JSONSerializer;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.common.service.CommonService;
import org.jeecgframework.core.interceptors.DateConvertEditor;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;


/**
 * 基础控制器，其他控制器需集成此控制器获得initBinder自动转换的功能
 * @author  张代浩
 *
 */
@Controller
@RequestMapping("/baseController")
public class BaseController {
	//wxj_wx 20170413
	public static final  String ACCOUNTID="accountid";

	/**
	 * 将前台传递过来的日期格式的字符串，自动转化为Date类型
	 *
	 * @param binder
	 */
	@InitBinder
	public void initBinder(ServletRequestDataBinder binder) {
//		SimpleDateFormat dateFormat = new SimpleDateFormat(
//				"yyyy-MM-dd hh:mm:ss");
//		binder.registerCustomEditor(Date.class, new CustomDateEditor(
//				dateFormat, true));
		binder.registerCustomEditor(Date.class, new DateConvertEditor());
	}

	/**
	 * 分页公共方法(非easyui)
	 *
	 * @author Alexander
	 * @date 20131022
	 */
	public List<?> pageBaseMethod(HttpServletRequest request,
			DetachedCriteria dc, CommonService commonService, int pageRow) {
		// 当前页
		// 总条数
		// 总页数

		int currentPage = 1;

		int totalRow = 0;
		int totalPage = 0;
		// 获取当前页
		String str_currentPage = request.getParameter("str_currentPage");
		currentPage = str_currentPage == null || "".equals(str_currentPage) ? 1
				: Integer.parseInt(str_currentPage);
		// 获取每页的条数
		String str_pageRow = request.getParameter("str_pageRow");
		pageRow = str_pageRow == null || "".equals(str_pageRow) ? pageRow
				: Integer.parseInt(str_pageRow);

		// 统计的总行数
		dc.setProjection(Projections.rowCount());

		totalRow = Integer.parseInt(commonService.findByDetached(dc).get(0)
				.toString());
		totalPage = (totalRow + pageRow - 1) / pageRow;

		currentPage = currentPage < 1 ? 1 : currentPage;
		currentPage = currentPage > totalPage ? totalPage : currentPage;
		// 清空统计函数
		dc.setProjection(null);
		// dc.setResultTransformer(dc.DISTINCT_ROOT_ENTITY);
		List<?> list = commonService.pageList(dc, (currentPage - 1) * pageRow,
				pageRow);

		request.setAttribute("currentPage", currentPage);
		request.setAttribute("pageRow", pageRow);
		request.setAttribute("totalRow", totalRow);
		request.setAttribute("totalPage", totalPage);
		return list;
	}

    /**
     * 抽取由逗号分隔的主键列表
     *
     * @param ids
     *            由逗号分隔的多个主键值
     * @return 主键类表
     * @author 张国明 2014-8-21 21:57:16
     */
    protected List<String> extractIdListByComma(String ids) {
        List<String> result = new ArrayList<String>();
        if (StringUtils.hasText(ids)) {
            for (String id : ids.split(",")) {
                if (StringUtils.hasLength(id)) {
                    result.add(id.trim());
                }
            }
        }

        return result;
    }
	/**
	 * 返回数据
	 * @param data
	 */
	protected void renderData(HttpServletResponse response, String data) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setCharacterEncoding("utf-8");
		PrintWriter printWriter = null;
		try {
			printWriter = response.getWriter();
			printWriter.print(data);
		} catch (IOException ex) {
		} finally {
			if (null != printWriter) {
				printWriter.flush();
				printWriter.close();
			}
		}
	}

	protected void renderData(HttpServletResponse response, Object data) {
			this.renderData(response, JSONSerializer.toJSON(data).toString());
	}

	public String uploadImage(MultipartFile upfile, EOSSFolderName folderName) throws Exception {
		String fileType = upfile.getContentType();
		String fileExtension = null;
		for (EFileType eFileType : EFileType.values()) {
			if (fileType.equals(eFileType.getTypeName())) {
				fileExtension = eFileType.getExtension();
				break;
			}
		}
		ResourceBundle bundle = PropertyResourceBundle.getBundle("OSS");
		String filePrefix = bundle.getString("file_prefix");
		String userPhoto = OSSFileOSUtil.uploadFile(folderName.getValue() + UUID.randomUUID() + fileExtension, upfile.getInputStream(), fileType);
		return filePrefix + userPhoto;
	}

	/**
	 * 获取带分页信息的Dategrid
	 * @param list
	 * @param dataGrid
	 * @return
	 */
	public DataGrid pageDateGrid(List list, DataGrid dataGrid){
		//转换为PageList
		PageList pageList = (PageList)list;
		Paginator page = pageList.getPaginator();
		//设置结果集
		dataGrid.setResults(list);
		//设置总条数
		dataGrid.setTotal(page.getTotalCount());
		//设置当前页
		dataGrid.setPage(page.getPage());
		//设置页大小
		dataGrid.setRows(page.getLimit());
		return dataGrid;
	}

	/**
	 * 获取页面参数
	 *
	 * @param request 请求对象
	 * @return 页面参数map
	 */
	protected Map getRequestParam(HttpServletRequest request) {
		Map<String,Object> map = new HashMap<String,Object>();
		Enumeration<String> names = request.getParameterNames();
		while (names.hasMoreElements()) {
			String name = names.nextElement();
			if("limit".equals(name) || "offset".equals(name)){
				map.put(name, Integer.valueOf(request.getParameter(name)));
			}
			map.put(name, request.getParameter(name));
		}
		//String userId = "test";//ResourceUtil.getSessionUserName().getId();
		//map.put("userId",userId);
		if(org.apache.commons.lang.StringUtils.isEmpty(request.getParameter("isPage"))){
			map.put("isPage","true");
		}
		return map;
	}

	/**
	 * 获取分页查询参数
	 *
	 * @param request
	 * @param dataGrid 参数封装
	 * @return 分页查询参数 map
	 */
	protected Map<String, Object> getPageQueryMap(HttpServletRequest request, DataGrid dataGrid) {
		Map<String, Object> map;
		map = getPageQueryMap(request);
		// 总页数
		int page = dataGrid.getPage();
		//每页最多展示数据条数
		int pageSize = dataGrid.getRows();
		//查询数据起始位置
		int begin = (page - 1) * pageSize;
		map.put("begin", begin);
		map.put("pageSize", pageSize);
		return map;
	}

	/**
	 * 获取查询参数
	 *
	 * @param request
	 * @return 查询参数map
	 */
	protected Map<String, Object> getPageQueryMap(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		//拼接查询参数参数信息
		Enumeration<String> parameterNames = request.getParameterNames();
		while (parameterNames.hasMoreElements()) {
			String nextEle = parameterNames.nextElement();
			String value = request.getParameter(nextEle);
			if (StringUtil.isNotEmpty(value)) {
				map.put(nextEle, value);
			}
		}
		//当前用户门店id
		map.put("curDepartId",  ResourceUtil.getSessionUserName().getCurrentDepart().getId());
		//当前用户id
		map.put("curUserId",  ResourceUtil.getSessionUserName().getId());
		return map;
	}
}
